<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Post extends Model
{


    protected $guarded = [];


    public function comments(){

        return $this->hasMany(Comment::class,'posts_id','id');

    }

    public function relBook(){

        return $this->belongsTo(Book::class,'book_num','book_num');

    }


    public function user(){

        return $this->belongsTo(User::class,'uid','id');

    }

    public function likes(){
        return $this->hasMany(PostsLikes::class,'posts_id','id');
    }

    public function likedUsers(){

        return $this->belongsToMany(User::class,'postslikes','posts_id','uid');

    }

    public function chapter(){

        return $this->hasOne(Chapter::class,'chapter_num','article_chapter');

    }

    public function bar(){

        return $this->belongsTo(Bar::class,'bar_num','bar_num');

    }


    public function getIsLikeAttribute(){

        if ( ! Auth::check() ){
            return false;
        }

        $user = Auth::user();

        $islike = $this->likedUsers()->where([
            'uid' => $user->id,
            'status' => 0

        ])->first();

        return !! $islike;

    }

    public function scopeToday($query)
    {

        $y = date("Y");

        $m = date("m");

        $d = date("d");
        $todayTime= mktime(0,0,0,$m,$d,$y);

        return $query->where('release_time', '>', $todayTime);
    }


    /**
     * 将当前帖子更新为热门帖子或者更新当前帖子热门时间
     * @return $this
     */
    public function toHot(){

        $this->hot_at = Carbon::now();
        $this->save();
        return $this;

    }


}
